let db = null // indexedDB实例
const request = window.indexedDB.open('xiaoceDB', 1) // 数据库名、版本号

request.onsuccess = (e) => {
  db = e.target.result
  console.log('你打开了indexedDB: ', db)
}

request.onerror = (e) => {
  console.log('打开indexedDB失败')
}

// onupgradeneeded事件会在初始化数据库/版本发生更新时被调用，我们在它的监听函数中创建object store
request.onupgradeneeded = (e) => {
  let objectStore
  // 如果同名表未被创建过，则新建test表
  if (!db.objectStoreNames.contains('test')) {
    objectStore = db.createObjectStore('test', { keyPath: 'id' })
  }
}

// 创建事务，指定表格名称和读写权限
const transaction = db.transaction(['test'], 'readwrite')
// 拿到Object Store对象
const objectStore = transaction.objectStore('test')
// 向表格写入数据
objectStore.add({ id: 1, name: 'xiuyan' })

// 操作成功时的监听函数
transaction.oncomplete = function (event) {
  console.log('操作成功')
}
// 操作失败时的监听函数
transaction.onerror = function (event) {
  console.log('这里有一个Error')
}
